<template>
  <div class="cart-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>购物车管理</h2>
    </div>

    <!-- 查询区域卡片 -->
    <el-card class="search-card">
      <el-row :gutter="10" justify="start" align="middle">
        <el-col :span="4">
          <label class="search-label">购物车id:</label>
          <el-input
              class="search-input"
              v-model="gouwuche.gwcid"
              placeholder="请输入购物车id"
          ></el-input>
        </el-col>
        <el-col :span="4">
          <label class="search-label">用户id:</label>
          <el-input
              class="search-input"
              v-model="gouwuche.yhid"
              placeholder="请输入用户id"
          ></el-input>
        </el-col>
        <el-col :span="4">
          <label class="search-label">菜品id:</label>
          <el-input
              class="search-input"
              v-model="gouwuche.cpid"
              placeholder="请输入菜品id"
          ></el-input>
        </el-col>
        <el-col :span="8">
          <el-space size="10">
            <el-button type="primary" @click="doList">查询</el-button>
            <el-button @click="reset">重置</el-button>
            <el-button type="success" @click="showAddDialog">新增购物车</el-button>
          </el-space>
        </el-col>
      </el-row>
    </el-card>

    <!-- 表格区域卡片 -->
    <el-card class="table-card">
      <el-table
          stripe
          :data="currentPageData"
          style="width: 100%"
          :header-cell-style="headerStyle"
          :row-class-name="rowClassName"
      >
        <el-table-column prop="gwcid" label="购物车id" width="120" sortable></el-table-column>
        <el-table-column prop="yhid" label="用户id" width="120" sortable></el-table-column>
        <el-table-column prop="cpid" label="菜品id" width="120" sortable></el-table-column>
        <el-table-column prop="cpsl" label="菜品数量" width="120" sortable></el-table-column>
        <el-table-column prop="cpdj" label="菜品单价" width="120" sortable></el-table-column>
        <el-table-column prop="cpzj" label="菜品总价" width="120" sortable></el-table-column>
        <el-table-column label="操作" width="280">
          <template #default="scope">
            <el-button type="info" size="small" @click="showDetailPage(scope.row)">详情</el-button>
            <el-button type="primary" size="small" @click="showUpdateDialog(scope.row)">修改</el-button>
            <el-button type="danger" size="small" @click="doDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <div class="pagination-container">
        <el-pagination
            background
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            :page-size="pageSize"
            :current-page="currentPage"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增 dialog-->
    <el-dialog v-model="addDialogVisible" title="新增购物车" width="40%" top="2vh" destroy-on-close>
      <add-guwuche
          @flushPage="reset"
          @closeDialog="addDialogVisible = false">
      </add-guwuche>
    </el-dialog>

    <!-- 更新 dialog-->
    <el-dialog v-model="updateDialogVisible" title="更新购物车" width="40%" top="2vh" destroy-on-close>
      <update-guwuche ref="updatePageRef"
                      @flushPage="reset"
                      @closeDialog="updateDialogVisible = false">
      </update-guwuche>
    </el-dialog>

    <!-- 详情 页面 -->
    <detail-gouwuche ref="detailPageRef"></detail-gouwuche>
  </div>
</template>

<script setup>
import {nextTick, onMounted, ref, computed} from 'vue'
import axios from "axios";
import {ElMessage} from "element-plus";
import AddGuwuche from "./AddGuwuche.vue";
import UpdateGuwuche from "./UpdateGuwuche.vue";
import DetailGouwuche from "./DetailGouwuche.vue";

const gouwuche = ref({
  gwcid: '',
  yhid: '',
  cpid: ''
})

const gouwucheList = ref([])

// 分页相关变量
const total = ref(0)
const pageSize = ref(5)
const currentPage = ref(1)

// 计算当前页的数据
const currentPageData = computed(() => {
  if (!Array.isArray(gouwucheList.value)) {
    return []; // 如果不是数组，返回空数组
  }

  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return gouwucheList.value.slice(start, end);
});

onMounted(() => {
  doList();
})

const doList = async () => {
  gouwucheList.value = []; // 初始化为一个空数组

  let url = '/api/gouwuche'; // 默认URL

  if (gouwuche.value.gwcid) {
    url = `/api/gouwuche/${gouwuche.value.gwcid}`;
  } else if (gouwuche.value.yhid) {
    url = `/api/gouwuche/by-yhid/${gouwuche.value.yhid}`;
  }  else if (gouwuche.value.cpid) {
    url = `/api/gouwuche/by-cpid/${gouwuche.value.cpid}`;
  }

  try {
    const { data } = await axios.get(url);
    console.log(data);

    if (data.code === 200) {
      // 确保 data.data 是一个数组
      gouwucheList.value = Array.isArray(data.data) ? data.data : [data.data];
      total.value = gouwucheList.value.length; // 设置总条数
      ElMessage.success('查询成功');
    } else {
      ElMessage.error(data.message);
    }
  } catch (error) {
    console.error('请求失败:', error);
    ElMessage.error('请求失败，请稍后重试');
  }
}

const reset = () => {
  gouwuche.value.gwcid = '';
  gouwuche.value.yhid = '';
  gouwuche.value.cpid = '';
  doList();
}

const addDialogVisible = ref(false)
const showAddDialog = () => {
  addDialogVisible.value = true;
}

const updateDialogVisible = ref(false)
const updatePageRef = ref();
const showUpdateDialog = (row) => {
  updateDialogVisible.value = true;
  nextTick(()=>{
    updatePageRef.value.handleUpdateData(row);
  })
}

// 详情 dialog
const detailPageRef = ref();
const showDetailPage = (obj)=>{
  detailPageRef.value.handleDetailData(obj);
}

const doDelete = async (row) => {
  const {data} = await axios.delete(`/api/gouwuche/${row.gwcid}`)
  console.log(data);
  if(data.code === 200){
    ElMessage.success('删除成功');
    await doList();
  }else{
    ElMessage.error(data.message);
  }
}

// 分页事件处理
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1 // 切换每页条数时，返回第一页
}

const handleCurrentChange = (val) => {
  currentPage.value = val
}
</script>

<style scoped>
.cart-container {
  padding: 20px;
  background-color: #f9f9f9;
  min-height: calc(100vh - 40px);
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  color: #f58147;
  font-weight: 600;
  margin: 0;
}

.search-card {
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.08);
  border-left: 4px solid #f58147;
}

.table-card {
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.08);
}

.search-label {
  color: #666;
  margin-right: 8px;
}

.search-input {
  width: 140px !important;
}

/* 表格样式 */
::v-deep .el-table__header th {
  background-color: #fff8f2;
  color: #f58147;
  font-weight: 500;
}

::v-deep .el-table__body tr:hover > td {
  background-color: #fff8f2 !important;
}

::v-deep .el-table--striped .el-table__body tr.el-table__row--striped td {
  background-color: #fffbf7;
}

/* 按钮样式覆盖 */
::v-deep .el-button--primary {
  background-color: #f58147;
  border-color: #f58147;
}

::v-deep .el-button--primary:hover {
  background-color: #e67030;
  border-color: #e67030;
}

::v-deep .el-button--success {
  background-color: dodgerblue;
  border-color: dodgerblue;
}

/* 分页居中 */
.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
</style>
